package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.reggie.pojo.AddressBook;
import com.reggie.service.AddressBookService;
import com.reggie.utils.BaseContext;
import com.reggie.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhaoyuheng
 * @email 2646498606@qq.com
 * @date 2022/4/27 16:31
 * todo
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增
     * @param addressBook
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody AddressBook addressBook) {
        log.info(addressBook.toString());
        //设置用户Id,通过专属线程获取
        Long userId = BaseContext.getCurrent();
        addressBook.setUserId(userId);
        //保存地址
        addressBookService.save(addressBook);
        return Result.success("添加成功！");
    }

    /**
     * 更改默认地址
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public Result<String> setDefault(@RequestBody AddressBook addressBook) {
        addressBookService.setDefault(addressBook);
        return Result.success("修改成功");
    }

    /**
     * 根据id查地址
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        log.info(addressBook.toString());
        return Result.success(addressBook);
    }

    /**
     * 查询默认地址
     * @return
     */
    @GetMapping("/default")
    public Result<AddressBook> getDefault() {
        //条件构造器
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        //找到默认状态为1的数据
        wrapper.eq(AddressBook::getIsDefault, 1);
        //查询
        AddressBook addressBook = addressBookService.getOne(wrapper);
        return Result.success(addressBook);
    }

    /**
     * 查询指定用户的所有地址
     * @return
     */
    @GetMapping("/list")
    public Result<List<AddressBook>> list() {
        //获得登录用户Id
        Long userId = BaseContext.getCurrent();
        //根据id查询当前用户的地址信息
        //查询条件
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, userId);

        List<AddressBook> list = addressBookService.list(wrapper);
        return Result.success(list);
    }

    /**
     * 更新地址
     * @param addressBook
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody AddressBook addressBook) {
        addressBookService.updateById(addressBook);
        return Result.success("更新成功");
    }
}
